//
//  j3GLView.m
//  HJC3D
//
//  Created by HJC on 11-10-10.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "j3GLView.h"
#import "j3RenderingEngine.h"
#import <OpenGLES/ES2/gl.h>


const bool ForceES1 = true;

@implementation j3GLView


+ (Class) layerClass
{
    return [CAEAGLLayer class];
}



- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        self.backgroundColor = [UIColor redColor];
        
        CAEAGLLayer* eaglLayer = (CAEAGLLayer*) super.layer;
        eaglLayer.opaque = YES;
        
        EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
        _context = [[EAGLContext alloc] initWithAPI:api];
        
        if (!_context || ForceES1) 
        {
            api = kEAGLRenderingAPIOpenGLES1;
            _context = [[EAGLContext alloc] initWithAPI:api];
        }
        
        if (!_context || ![EAGLContext setCurrentContext:_context]) 
        {
            [self release];
            return nil;
        }
        
        if (api == kEAGLRenderingAPIOpenGLES1) 
        {
            NSLog(@"Using OpenGL ES 1.1");
            _renderingEngine = CreateRenderer1();
        }
        else 
        {
            NSLog(@"Using OpenGL ES 2.0");
            _renderingEngine = CreateRenderer2();
        }
        
        [_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:eaglLayer];        
        _renderingEngine->initialize(CGRectGetWidth(frame), CGRectGetHeight(frame));
        
        [self drawView: nil];
        _timestamp = CACurrentMediaTime();
        
        CADisplayLink* displayLink;
        displayLink = [CADisplayLink displayLinkWithTarget:self 
                                                  selector:@selector(drawView:)];
        
        [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        
        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(didRotate:)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil];
    }
    return self;
}



- (void) drawView: (CADisplayLink*) displayLink
{
    if (displayLink != nil) 
    {
        float elapsedSeconds = displayLink.timestamp - _timestamp;
        _timestamp = displayLink.timestamp;
        _renderingEngine->updateAnimation(elapsedSeconds);
    }
    
    _renderingEngine->render();
    [_context presentRenderbuffer:GL_RENDERBUFFER];
}



- (void) didRotate: (NSNotification*) notification
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    _renderingEngine->onRotate((DeviceOrientation) orientation);
    [self drawView:nil];
}


@end
